﻿using System;
using Newtonsoft.Json;

namespace QQ2564874169.Core.Json.Newtsjson
{
    public class LongToStringConverter : Newtonsoft.Json.JsonConverter
    {
        private static ulong _max;
        private static int _convertByLength;

        public static int ConvertByLength
        {
            get { return _convertByLength; }
            set
            {
                _convertByLength = value;
                _max = (ulong) Math.Pow(10, _convertByLength);
            }
        }

        static LongToStringConverter()
        {
            ConvertByLength = 16;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var v = value is long ? (ulong) (long) value : (ulong) value;
            if (v >= _max)
            {
                writer.WriteValue(v.ToString());
                return;
            }
            writer.WriteValue(value);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            return reader.Value;
        }

        public override bool CanConvert(Type t)
        {
            if (ConvertByLength < 1)
                return false;

            return t == typeof(long?) || t == typeof(long) ||
                   t == typeof(ulong) || t == typeof(ulong?);
        }
    }
}
